package com.google.android.apps.iosched.ui;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.AccountUtils;
import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;

import java.util.Arrays;
import java.util.List;

import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
 * 账户登录
 * Created by Alex on 13-11-29.
 */
public class AccountActivity extends SherlockFragmentActivity implements AccountUtils.AuthenticateCallback{

    private static final String TAG = makeLogTag(AccountActivity.class);

    public static final int REQUEST_AUTHENTICATE = 100;

    /**
     * 这个是从AccountUtil里面启动AccountActivity的Intent里面包含的字段
     */
    public static final String EXTRA_FINISH_INTENT = "com.google.android.iosched.extra.FINISH_INTENT";

    private final Handler mHandler = new Handler();

    private Account mChosenAccount;

    private Intent mFinishIntent;

    private boolean mCancelAuth = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_account);

        if (getIntent().hasExtra(EXTRA_FINISH_INTENT)){
            mFinishIntent = getIntent().getParcelableExtra(EXTRA_FINISH_INTENT);

        }

        /**
         * 第一次启动该Activity，加载ChooseAccountFragment
         */
        if (savedInstanceState == null){
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container,new ChooseAccountFragment(),"choose_account")
                    .commit();
        }
    }

    /**
     * ListFragment  显示手机上得账户
     */
    public static class ChooseAccountFragment extends SherlockListFragment{
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //在actionbar 上显示menu item
            setHasOptionsMenu(true);
        }


        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            inflater.inflate(R.menu.add_account,menu);
            super.onCreateOptionsMenu(menu,inflater);
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {

            if (item.getItemId() == R.id.menu_add_account) {
                //手动的使用设置里面的账户添加account
                Intent addAccountIntent = new Intent(Settings.ACTION_ADD_ACCOUNT);
                addAccountIntent.putExtra(Settings.EXTRA_AUTHORITIES, new String[]{ScheduleContract.CONTENT_AUTHORITY});
                startActivity(addAccountIntent);
                return true;
            }

            return super.onOptionsItemSelected(item);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_login_choose_account,container,false);
            TextView descriptionView = (TextView) rootView.findViewById(R.id.choose_account_intro);
            descriptionView.setText(Html.fromHtml(getString(R.string.description_choose_account)));
            return rootView;
        }

        private AccountListAdapter mAccountListAdapter;

        private void reloadAccountList(){
            if (mAccountListAdapter != null){
                mAccountListAdapter = null;
            }

            AccountManager am = AccountManager.get(getActivity());
            Account[] accounts = am.getAccountsByType(GoogleAccountManager.ACCOUNT_TYPE);
            mAccountListAdapter = new AccountListAdapter(getActivity(), Arrays.asList(accounts));
            setListAdapter(mAccountListAdapter);
        }

        private class AccountListAdapter extends ArrayAdapter<Account>{

            private static final int LAYOUT_RESOURCE = android.R.layout.simple_list_item_1;

            public AccountListAdapter(Context context,List<Account> accounts) {
                super(context,LAYOUT_RESOURCE, accounts);
            }

            //缓存holder
            private class ViewHolder{
                TextView text1;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder viewHolder;

                if (convertView == null){
                    convertView = getLayoutInflater(null).inflate(LAYOUT_RESOURCE,null);
                    viewHolder = new ViewHolder();
                    viewHolder.text1 = (TextView) convertView.findViewById(android.R.id.text1);
                    convertView.setTag(viewHolder);
                }else{
                    viewHolder = (ViewHolder) convertView.getTag();
                }
                //父类的方法
                final Account account = getItem(position);
                if (account != null){
                    viewHolder.text1.setText(account.name);
                }else{
                    viewHolder.text1.setText("");
                }

                return convertView;
            }
        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
            super.onListItemClick(l, v, position, id);
        }

        @Override
        public void onResume() {
            super.onResume();
            reloadAccountList();
        }
    }

    /**
     * 实现自AccountUtil
     * @return
     */
    @Override
    public boolean shouldCanceAuthentication() {



            return false;
    }

    @Override
    public void onAuthTokenAvailable(String authToken) {

    }
}
